package gw.com.android.ui.chart;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.Collections;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.app.AppContances;
import gw.com.android.model.DataManager;
import gw.com.android.ui.quote2.widget.OnQuoteChartProgressStatusChangeListener;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.DoubleConverter;
import www.com.library.util.ProductPrecision;
import www.com.library.util.StringFormatter;

/**
 * Created by reeta.zou on 2016/10/13.
 * 价格明细界面
 */
public class ChartDetailFragment extends PushMsgTabFragment {

    @BindView(R.id.chart_detail_root)
    LinearLayout mRoot;
    @BindView(R.id.list_view)
    RecyclerView mListView;

    private int mUiCode;//产品code
    private int zoneType;//产品板块
    private DataItemResult mListData;//界面显示数据集合
    private DataItemResult mTmpData;//临时缓存数据
    private ProductPrecision mPrecision;
    private DataAdapter mAdapter;
    private OnQuoteChartProgressStatusChangeListener onStatusChangeListener;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chart_detail;
    }

    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);
        mUiCode = getArguments().getInt("uiCode", 0);
        zoneType = getArguments().getInt("zoneType", GTSConst.ZONE_TYPE_SELF);
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
        // 设置布局管理器
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //mListView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL));
        mListData = new DataItemResult();
        mTmpData = new DataItemResult();
        mAdapter = new DataAdapter(getActivity());
        mListView.setAdapter(mAdapter);
    }

    @Override
    protected void initViewData() {
        DataItemDetail model = DataManager.instance().getTickModel(mUiCode);
        if (null != model) {
            mPrecision = new ProductPrecision(model.getInt(GTSConst.JSON_KEY_DIGITS));
            DataItemDetail curTick = new DataItemDetail();
            updateTick(curTick, model);
            mTmpData.addItem(curTick);
            mListData.addItem(curTick);
        }
        mAdapter.notifyDataSetChanged();

        if (onStatusChangeListener != null) {
            onNightMode(onStatusChangeListener.isNight());
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initViewData();
        }
    }

    /**
     * 更新报价
     */
    private void updateTick(DataItemDetail curTick, DataItemDetail model) {
        curTick.setStringValue(GTSConst.JSON_KEY_CURPRICEMAP, model.getString(GTSConst.JSON_KEY_CURPRICEMAP));
        curTick.setIntValue(GTSConst.JSON_KEY_TIME, model.getInt(GTSConst.JSON_KEY_TIME));
        curTick.setIntValue(GTSConst.JSON_KEY_CURPRICEARRAW, AppContances.ARRAW_HIDE);
        curTick.setIntValue(GTSConst.JSON_KEY_CURPRICESTATE, model.getInt(GTSConst.JSON_KEY_CURPRICESTATE));
    }

    /**
     * 刷新产品更新
     */
    public void onRefreshSymbol(DataItemDetail model) {
        if (null != model) {
            mPrecision = new ProductPrecision(model.getInt(GTSConst.JSON_KEY_DIGITS));
            dealPriceColor(mTmpData);
            mListData.clear();
            mListData.appendItems(mTmpData);
            Collections.reverse(mListData.getDataList());
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 设置小数位方法
     */
    public void setPrecision(DataItemDetail model) {
        if (null != model) {
            mPrecision = new ProductPrecision(model.getInt(GTSConst.JSON_KEY_DIGITS));
        }
    }

    /**
     * 刷新报价
     */
    public void onRefreshPrice(DataItemDetail model) {
        /* 异常情况处理 **/
        if (null == mTmpData) return;
        Logger.e("QCMD_RES_PERTICK onRefreshPrice 111== " + StringFormatter.instance().secToTime(model.getInt(GTSConst.JSON_KEY_TIME))
                + (model.getInt(GTSConst.JSON_KEY_CODEID) == mUiCode) + ", " + (mTmpData.getDataCount() > 0));
        if (mTmpData.getDataCount() > 0 && null != model && null != mAdapter && model.getInt(GTSConst.JSON_KEY_CODEID) == mUiCode) {
            Logger.e("QCMD_RES_PERTICK onRefreshPrice222 == " + model.getString(GTSConst.JSON_KEY_CURPRICEMAP));
            DataItemDetail curTick = new DataItemDetail();
            updateTick(curTick, model);
            mTmpData.addItem(curTick);
            // 只保留最新的50条数据，超过将清除最先插入的数据
            if (mTmpData.getDataCount() > 50) {
                mTmpData.removeByIndex(0);
            }
            dealPriceColor(mTmpData);
            mListData.clear();
            mListData.appendItems(mTmpData);
            Collections.reverse(mListData.getDataList());
            mAdapter.notifyDataSetChanged();
        }
    }

    private void dealPriceColor(DataItemResult result) {
        for (int position = 0; position < result.getDataCount(); position++) {
            DataItemDetail item = result.getItem(position);
            if (position == 0) {
                item.setIntValue(GTSConst.JSON_KEY_CURPRICEARRAW, AppContances.ARRAW_HIDE);
            } else {
                DataItemDetail preItem = result.getItem(position - 1);
                float price = DoubleConverter.toFloat(mPrecision.mNumOfDecimalsPoint, DoubleConverter.toFloatData(item.getString(GTSConst.JSON_KEY_CURPRICEMAP)));
                float prePrice = DoubleConverter.toFloat(mPrecision.mNumOfDecimalsPoint, DoubleConverter.toFloatData(preItem.getString(GTSConst.JSON_KEY_CURPRICEMAP)));
                if (price > prePrice) {
                    //如果当前报价跟上口报价不一致，根据涨跌方向显示颜色和箭头
                    item.setIntValue(GTSConst.JSON_KEY_CURPRICESTATE, AppContances.PRICE_INCREASE);
                    item.setIntValue(GTSConst.JSON_KEY_CURPRICEARRAW, AppContances.ARRAW_SHOW);
                } else if (price < prePrice) {
                    //如果当前报价跟上口报价不一致，根据涨跌方向显示颜色和箭头
                    item.setIntValue(GTSConst.JSON_KEY_CURPRICESTATE, AppContances.PRICE_DECREASE);
                    item.setIntValue(GTSConst.JSON_KEY_CURPRICEARRAW, AppContances.ARRAW_SHOW);
                } else {
                    //当前报价跟上口报价一致，根据上一口报价涨跌方向显示颜色，不要箭头
                    item.setIntValue(GTSConst.JSON_KEY_CURPRICESTATE, preItem.getInt(GTSConst.JSON_KEY_CURPRICESTATE));
                    item.setIntValue(GTSConst.JSON_KEY_CURPRICEARRAW, AppContances.ARRAW_HIDE);
                }
            }
        }
    }

    /**
     * 清除界面数据
     */
    public void clearData() {
        if (null != mTmpData) {
            mTmpData.clear();
        }
        if (null != mListData) {
            mListData.clear();
        }
    }

    /**
     * 列表适配器
     *
     * @author reeta
     */
    public class DataAdapter extends RecyclerView.Adapter {
        private LayoutInflater mInflater;
        private boolean isNight = false;

        public DataAdapter(Activity act) {
            mInflater = LayoutInflater.from(act);
        }

        public void setNight(boolean isNight) {
            this.isNight = isNight;
            notifyDataSetChanged();
        }

        public DataItemDetail getItem(int position) {
            if (position < 0 || position >= mListData.getDataCount())
                return null;
            return mListData.getItem(position);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = mInflater.inflate(R.layout.list_item_chart_detail, parent, false);
            return new ItemView(itemView);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ItemView viewHold = (ItemView) holder;
            if (position % 2 == 0) {
                if (isNight) {
                    viewHold.itemView.setBackgroundColor(getResources().getColor(R.color.color_night_bg_d));
                } else {
                    viewHold.itemView.setBackgroundColor(ColorThemeUtil.instance().color_a);
                }
            } else {
                if (isNight) {
                    viewHold.itemView.setBackgroundColor(getResources().getColor(R.color.color_night_bg));
                } else {
                    viewHold.itemView.setBackgroundColor(ColorThemeUtil.instance().color_e);
                }
            }

            DataItemDetail item = getItem(position);
            if (null != item && null != mPrecision) {
                float price = DoubleConverter.toFloat(mPrecision.mNumOfDecimalsPoint, DoubleConverter.toFloatData(item.getString(GTSConst.JSON_KEY_CURPRICEMAP)));
                viewHold.mView.setText(StringFormatter.instance().secToTime(item.getInt(GTSConst.JSON_KEY_TIME)));
                viewHold.mPriceView.setText(mPrecision.format(price));
                ColorThemeUtil.instance().setPriceColor(viewHold.mPriceView, item.getInt(GTSConst.JSON_KEY_CURPRICESTATE),
                        item.getInt(GTSConst.JSON_KEY_CURPRICEARRAW), true);
            }

        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            if (null != mListData) {
                return mListData.getDataCount();
            }
            return 0;
        }

        class ItemView extends RecyclerView.ViewHolder {

            @BindView(R.id.chart_time)
            TextView mView;
            @BindView(R.id.chart_price)
            TextView mPriceView;

            public ItemView(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    public void onNightMode(boolean isNight) {
        if (isNight) {
            mRoot.setBackgroundColor(getResources().getColor(R.color.color_night_bg_d2));
        } else {
            mRoot.setBackgroundColor(getResources().getColor(R.color.color_f));
        }
        if (mAdapter != null) {
            mAdapter.setNight(isNight);
        }
    }

    public void setOnStatusChangeListener(OnQuoteChartProgressStatusChangeListener onStatusChangeListener) {
        this.onStatusChangeListener = onStatusChangeListener;
    }

    public void setUiCodeAndZoneType(int uiCode, int zoneType) {
        this.mUiCode = uiCode;
        this.zoneType = zoneType;
        clearData();
        initViewData();
    }

}
